﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.Utils
{
    public static class SystemUtils
    {


        public static class ArgUtils
        {
            private static string FindKey(string str)
            {
                int index = str.IndexOf('=');
                if (index <= 0)
                {
                    return str; // 全字段
                }
                string key = str.Substring(0, index);
                return key;
            }

            private static string FindValue(string str)
            {
                int index = str.IndexOf('=');
                if (index <= 0)
                {
                    return ""; // 空
                }
                string key = str.Substring(index + 1);
                return key;
            }

            /// <summary>
            /// 处理系统参数<br>
            ///* 例子:<br>
            ///* -out=asfd -in=124
            /// </summary>
            public static Dictionary<string, string> SystemArgs(string[] args)
            {
                int asize = (args != null) ? args.Length : 0;
                var argMap = new Dictionary<string, string>(asize);
                // 遍历解析
                for (int i = 0; i < asize; i++)
                {
                    string arg = args[i];
                    if (arg == null)
                    {
                        continue;
                    }

                    // 解析
                    string key = FindKey(arg);
                    if (key == null || key.Length <= 0)
                    {
                        continue;
                    }
                    key = key.Trim(); // 去除空格

                    // 解析参数
                    string value = FindValue(arg);
                    if (value == null || value.Length <= 0)
                    {
                        continue;
                    }
                    value = value.Trim(); // 去除空格

                    // 插入数据
                    argMap[key] = value;
                }

                return argMap;
            }

            /// <summary>
            /// 解析参数<br>
            /// * 例子: a=2,b=3
            /// </summary>
            public static Dictionary<string, string> getArgs(string args0)
            {
                string[] args = args0.Split(',');
                return SystemArgs(args);
            }

            public static T GetArg<T>(string value, T defualt)
            {
                if (value == null || value.Length <= 0)
                {
                    return defualt;
                }
                // 读取基础值
                T obj = Utils.ToValue<T>(value);
                if (obj == null)
                {
                    return defualt;
                }
                return obj;
            }

        }
    }
}
